package com.gitee.fanx.rpc;

import com.fasterxml.jackson.databind.JavaType;
import org.springframework.core.ResolvableType;

import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.IntStream;

public class JavaTypeResolver {

	private static JavaType resolve(ResolvableType resolvableType) {
		if (resolvableType.getGenerics().length == 0) {
			return RpcCodec.JSON_MAPPER.constructType(resolvableType.resolve());
		}
		JavaType[] javaTypes = new JavaType[resolvableType.getGenerics().length];
		for (int i = 0; i < resolvableType.getGenerics().length; i++) {
			javaTypes[i] = resolve(resolvableType.getGeneric(i));
		}
		return RpcCodec.JSON_MAPPER.getTypeFactory().constructParametricType(resolvableType.resolve(), javaTypes);
	}

	public static JavaType methodReturnType(Method method) {
		return resolve(ResolvableType.forMethodReturnType(method));
	}

	public static List<JavaType> methodParameters(Method method) {
		return IntStream.range(0, method.getParameterCount())
			.mapToObj(x -> ResolvableType.forMethodParameter(method, x))
			.map(JavaTypeResolver::resolve).toList();
	}
}
